﻿namespace Digitalmes.Application.Sys.Orgs.Commands;

/// <summary>
/// 更新组织机构命令。
/// </summary>
/// <param name="Org"></param>
public record UpdateOrgCommand(SysOrgDto Org) : IRequest<IResult<bool>>;

internal sealed class UpdateOrgCommandHandler(IRepository<SysOrg> repo) : IRequestHandler<UpdateOrgCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateOrgCommand request, CancellationToken cancellationToken)
    {
        // 检查机构代码是否已存在。
        if (await repo.IsAnyAsync(m => m.Code == request.Org.Code && m.Id != request.Org.Id, cancellationToken))
        {
            return Result.Failure("组织编号已存在");
        }

        var org = request.Org.Adapt<SysOrg>();
        var ok = await repo.UpdateAsync(org, m => new {
            m.Name,
            m.Code,
            m.Principal,
            m.Phone,
            m.Email,
            m.Sort,
            m.Remark,
            m.Status,
            m.LastModifiedBy,
            m.LastModifiedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}

